import { serverErr, projectErr } from './errorHandle'
import { storageSyncCache } from '@/utils/storage'

interface ResponseData<T> {
  code?: number
  data?: T
  msg?: string
}

const timeout: number = 60000

const get = <T>(
  url: string,
  params: any,
  config?: UniApp.RequestOptions
): Promise<ResponseData<T>> => {
  return new Promise((resolve, reject) => {
    const Authorization: string | null = storageSyncCache.get('Authorization')
    const requestParams: UniApp.RequestOptions = {
      method: 'GET',
      url: import.meta.env.VITE_APP_API_ROOT + url,
      data: params,
      timeout: timeout,
      success: (response: any) => {
        const resData = response.data
        const responseOk = import.meta.env.VITE_APP_API_STATUS_OK
        if (String(resData.code) !== String(responseOk)) {
          projectErr[resData.code as keyof typeof projectErr]
            ? projectErr[resData.code as keyof typeof projectErr](resData.msg)
            : projectErr[500](resData.msg)
        }
        resolve(response.data)
      },
      fail: (error: any) => {
        serverErr && serverErr()
        reject(error)
      },
      ...(config || {}),
    }

    if (Authorization) {
      requestParams.header = {
        ...(requestParams.header || {}),
        Authorization,
      }
    }

    uni.request(requestParams)
  })
}

const post = <T>(
  url: string,
  params: any,
  config?: UniApp.RequestOptions
): Promise<ResponseData<T>> => {
  return new Promise((resolve, reject) => {
    const Authorization: string | null = storageSyncCache.get('Authorization')
    const requestParams: UniApp.RequestOptions = {
      method: 'POST',
      url: import.meta.env.VITE_APP_API_ROOT + url,
      data: params,
      timeout: timeout,
      header: {
        'Content-Type': 'application/json',
      },
      success: (response: any) => {
        const resData = response.data
        const responseOk = import.meta.env.VITE_APP_API_STATUS_OK
        if (String(resData.code) !== String(responseOk)) {
          projectErr[resData.code as keyof typeof projectErr]
            ? projectErr[resData.code as keyof typeof projectErr](resData.msg)
            : projectErr[500](resData.msg)
        }
        resolve(resData)
      },
      fail: (error: any) => {
        serverErr && serverErr()
        reject(error)
      },
      ...(config || {}),
    }

    if (Authorization) {
      requestParams.header = {
        ...(requestParams.header || {}),
        Authorization,
      }
    }

    uni.request(requestParams)
  })
}

export default {
  get,
  post,
}
